/**   
* 所属公司：稻普控股集团
* 项目名称：dpqc-parent-manager-home   
* 类名称：PowerController   
* 类描述：   
* 创建人：zhangpp
* 创建时间：2017年4月7日 下午12:30:06   
* 修改人：zhangpp
* 修改时间：2017年4月7日 下午12:30:06   
* 修改备注：   
* @version V1.0     
*/ 
package com.zjdiepu.www.manage.api.base;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Id;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.lang.ZNode;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.ibiz.base.ISysPowerService;
import com.zjdiepu.www.model.base.dto.SysPower;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.base.ext.SysPowerExt;
import com.zjdiepu.www.model.base.response.Nemu;

/**   
 * 所属公司：稻普控股集团
 * 项目名称：dpqc-parent-manager-home   
 * 类名称：SysPowerController   
 * 类描述：   
 * 创建人：zhangpp
 * 创建时间：2017年4月7日 下午12:30:06   
 * 修改人：zhangpp
 * 修改时间：2017年4月7日 下午12:30:06   
 * 修改备注：   
 * @version V1.0     
 */
@RestController
@RequestMapping("power")
public class SysPowerController extends BaseController {
	@Autowired
	private ISysPowerService sysPowerService;
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getList  <br/>
	 * @Description: 权限列表 <br/>
	 * @param powerExt
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping(value="getNemus", method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public ApiResponse getNemus(String powerCode) {
		SysUser currentUser =(SysUser)getCurrentUser();
		Map<String, List<Nemu>> map = CollectionInitUtil.emptyMap();
		Map<String, List<Nemu>> userNemus = currentUser.getNemus();
		if(null != userNemus) {
			List<Nemu> top = userNemus.get("top");
			map.put("top", top);
			if(StringUtils.isBlank(powerCode)) {
				Nemu nemu = top.get(0);
				powerCode = nemu.getPowerCode();
			}
			List<Nemu> nemus = userNemus.get(powerCode);
			map.put("nemus", nemus);
		}
		return ApiResponse.success(map);
	}

	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getList  <br/>
	 * @Description: 权限列表 <br/>
	 * @param powerExt
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping(value="getList", method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public ApiResponse getList(@ModelAttribute SysPowerExt powerExt) {
		powerExt.notDeleted();
		PageVo page = getPage(powerExt);
		int records = sysPowerService.countByExt(powerExt);
		page.setRecords(records);
		if(records > 0){
			List<SysPower> powers = sysPowerService.selectByExt(powerExt);
			page.setRows(powers);
		} else {
			page.setRows(CollectionInitUtil.emptyList());
		}
		List<SysPower> powers = sysPowerService.selectByExt(powerExt);
		return ApiResponse.success(powers);
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getPowerList  <br/>
	 * @Description: 查询所有菜单权限 <br/>
	 * @param sysPowerExt
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping(value="getPowerList", method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public ApiResponse getPowerList(@ModelAttribute SysPowerExt sysPowerExt) 
	{
		sysPowerExt.notDeleted();
		sysPowerExt.withOutPage();
		sysPowerExt.setOrderSql("`SORT_VALUE` ASC");
		List<SysPower> result = sysPowerService.selectByExt(sysPowerExt);
		return ApiResponse.success(result);
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getPowerListForShotcut  <br/>
	 * @Description: 快捷方式菜单 <br/>
	 * @param sysPowerExt
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping(value="getPowerListForShortcut", method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public ApiResponse getPowerListForShortcut(@ModelAttribute SysPowerExt sysPowerExt) {
		AbstractSysUser currentUser = getCurrentUser();
		String userId = currentUser.getId();
		sysPowerExt.setBaseWhere();
		sysPowerExt.withOutPage();
		sysPowerExt.setUserId(userId);
		sysPowerExt.setMenuStatus(1);
		sysPowerExt.setOrderSql("`SORT_VALUE` ASC");
		List<SysPower> result = sysPowerService.selectByExt(sysPowerExt);
		return ApiResponse.success(result);
	}

	/**
	 * @author xiongxiaotun <br/>
	 * @Title: queryOne  <br/>
	 * @Description: 权限详情 <br/>
	 * @param id
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping(value = "getById", method = RequestMethod.POST)
	public ApiResponse queryOne(String id) {
		if(StringUtils.isBlank(id)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY.getCode(), "请选择权限");
		}
		SysPower power = sysPowerService.selectById(id);
		if(null == power) {
			return ApiResponse.fail(ResultFlagType.MISSING.getCode(), "权限不存在");
		}
		return ApiResponse.success(power);
	}

	/**
	 * 添加权限
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param user
	 * @return
	 */
	@RequestMapping(value = { "add" }, method = { RequestMethod.POST })
	public ApiResponse add(@Validated(Add.class) SysPower power) {
		AbstractSysUser currentUser = getCurrentUser();
		
		SysPower sysPower = new SysPower();
		sysPower.notDeleted();
		sysPower.setPowerCode(power.getPowerCode());
		boolean repeatCode = sysPowerService.repeat(sysPower);
		if(repeatCode) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "权限编码重复");
		}
		
		sysPower.setPowerCode(null);
		sysPower.setParentId(power.getParentId()); //一级下才不允许重复
		sysPower.setName(power.getName());
		boolean repeatName = sysPowerService.repeat(sysPower);
		if(repeatName) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "权限名称重复");
		}
		
		power.setModifierName(currentUser.getName());
		power.setModifier(currentUser.getId());
		sysPowerService.saveUpdateAndDelete(power, OperateType.add);
		return ApiResponse.success(true);
	}
	
	/**
	 * 修改权限
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param user
	 * @return
	 */
	@RequestMapping(value = { "modify" }, method = { RequestMethod.POST })
	public ApiResponse modify(@Validated(Update.class) SysPower power) {
		AbstractSysUser currentUser = getCurrentUser();
		
		SysPower sysPower = new SysPower();
		sysPower.notDeleted();
		sysPower.setId(power.getId());
		sysPower.setParentId(power.getParentId()); //一级下才不允许重复
		sysPower.setName(power.getName());
		boolean repeatName = sysPowerService.repeat(sysPower);
		if(repeatName) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "权限名称重复");
		}
		sysPower.setName(null);
		sysPower.setPowerCode(power.getPowerCode());
		boolean repeatCode = sysPowerService.repeat(sysPower);
		if(repeatCode) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "权限编码重复");
		}
		
		power.setModifierName(currentUser.getName());
		power.setModifier(currentUser.getId());
		sysPowerService.saveUpdateAndDelete(power, OperateType.edit);
		return ApiResponse.success(true);
	}


	/**
	 * 权限删除
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param user
	 * @return
	 */
	@RequestMapping(value = { "del" }, method = { RequestMethod.POST })
	public ApiResponse del(@Validated(Id.class) SysPower power) {
		AbstractSysUser currentUser = getCurrentUser();
		for(String powerId : power.getId().split(",")) {
			if(StringUtils.isBlank(powerId)) {
				continue;
			}
			SysPower power_ = new SysPower();
			power_.setId(powerId);
			power_.setModifierName(currentUser.getName());
			power_.setModifier(currentUser.getId());
			sysPowerService.saveUpdateAndDelete(power_, OperateType.delete);
		}
		return ApiResponse.success(true);
	}
	
	/**
	 * APP菜单树形结构
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param powerExt
	 * @return
	 */
	@RequestMapping(value = { "queryTree" }, method = { RequestMethod.POST })
	public ApiResponse queryTree(String roleId) {
		if(StringUtils.isBlank(roleId)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY.getCode(), "请选择角色");
		}
		List<SysPower> sysPowers = sysPowerService.selectByRoleId(null);
		
		List<SysPower> userPowers = sysPowerService.selectByRoleId(roleId);
		
		final Set<String> hasPowers = CollectionUtils.isEmpty(userPowers) ? new HashSet<>() :userPowers.stream().map(userPower -> userPower.getId()).collect(Collectors.toSet());
		
		List<ZNode>  znodes = new ArrayList<ZNode>();
		if(CollectionUtils.isNotEmpty(sysPowers)) {
			znodes = sysPowers.stream().map(power -> new ZNode(power.getId(), power.getParentId(), power.getPowerCode(), power.getName(), true, hasPowers.contains(power.getId()))).collect(Collectors.toList());
		}
		return ApiResponse.success(znodes);
	}
	
	/**
	 * 权限禁用
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param userExt
	 * @return
	 */
	@RequestMapping(value = { "disable" }, method = { RequestMethod.POST })
	public ApiResponse disable(@Validated(Id.class) SysPower power) {
		AbstractSysUser currentUser = getCurrentUser();
		for(String powerId : power.getId().split(",")) {
			if(StringUtils.isBlank(powerId)) {
				continue;
			}
			SysPower power_ = new SysPower();
			power_.setId(powerId);
			power_.setDpStatus(DpStatus.INVALID.getCode());
			power_.setModifierName(currentUser.getName());
			power_.setModifier(currentUser.getId());
			sysPowerService.saveUpdateAndDelete(power_, OperateType.edit);
		}
		return ApiResponse.success(true);
	}
	
	/**
	 * 权限激活
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param userExt
	 * @return
	 */
	@RequestMapping(value = { "enable" }, method = { RequestMethod.POST })
	public ApiResponse enable(@Validated(Id.class) SysPower power) {
		AbstractSysUser currentUser = getCurrentUser();
		for(String powerId : power.getId().split(",")) {
			if(StringUtils.isBlank(powerId)) {
				continue;
			}
			SysPower power_ = new SysPower();
			power_.setId(powerId);
			power_.setDpStatus(DpStatus.NORMAL.getCode());
			power_.setModifierName(currentUser.getName());
			power_.setModifier(currentUser.getId());
			sysPowerService.saveUpdateAndDelete(power_, OperateType.edit);
		}
		return ApiResponse.success(true);
	}
	
	/**
	 * 查询所有快捷方式
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @return
	 */
	@RequestMapping(value = { "queryQuick" }, method = { RequestMethod.POST })
	public ApiResponse queryQuick() {
		AbstractSysUser currentUser = getCurrentUser();
		List<SysPower> quicks = sysPowerService.selectQuickByUserId(currentUser.getId());
		return ApiResponse.success(quicks);
	}
}
